import os
import shutil

from docx import Document

import DataGrouping
import TableData
import WordHelper

from pathlib import Path


def divideARTable(doc: Document):
    tableDict = {}
    for table_index, table in enumerate(doc.tables):
        print("table:", type(table))
        tableFound = False
        for row_index, row in enumerate(table.rows):
            if tableFound:
                continue
            for col_index, cell in enumerate(row.cells):
                if tableFound:
                    continue
                clean_text = cell.text.strip()
                if col_index == 0 and row_index == 0:
                    print(f"info -- 第一单元格{clean_text}, table {table_index}")
                if col_index == 0 and row_index == 0:
                    if clean_text.startswith(WordHelper.ETableAR.kModel.value):
                        tableDict[WordHelper.ETableAR.kModel.value] = table
                        tableFound = True
                    elif clean_text.startswith(WordHelper.ETableAR.kSeq.value):
                        tableDict[WordHelper.ETableAR.kSeq.value] = table
                        tableFound = True
                    elif clean_text.startswith(WordHelper.ETableAR.kPart.value):
                        tableDict[WordHelper.ETableAR.kPart.value] = table
                        tableFound = True
                    elif clean_text.startswith(WordHelper.ETableAR.kRef.value):
                        tableDict[WordHelper.ETableAR.kRef.value] = table
                        tableFound = True
                    elif clean_text.startswith(WordHelper.ETableAR.kEng.value):
                        tableDict[WordHelper.ETableAR.kEng.value] = table
                        tableFound = True

        if not tableFound:
            raise ValueError("非在记录表格")
    return tableDict


def process_word_template_ar(configFilePath, groupedData: DataGrouping.GroupData) -> Path:
    print(configFilePath)

    header = groupedData.header
    if not isinstance(header, TableData.Header):
        raise Exception("读取头部信息失败")

    target_file_name = header.no

    source_file_path = configFilePath + '\\F010203-02装配制造记录Rev.8.docx'
    copied_file_path = configFilePath + f'\\AR_{target_file_name}.docx'

    # 确保源文件存在
    if not os.path.exists(source_file_path):
        raise FileNotFoundError(f"源文件不存在: {source_file_path}")

    # 复制文件
    shutil.copy2(source_file_path, copied_file_path)

    # 打开文档
    doc = Document(copied_file_path)

    # 获取第一个表格用于写入
    if not doc.tables:
        raise ValueError("文档中没有表格")

    # 页眉表格处理
    fillHeader(doc, groupedData)

    # 表格分离
    tableInfoDictAR = {}  # TableE --> TableInfo
    tableDictAR = divideARTable(doc)
    for t in WordHelper.ETableAR:
        if tableDictAR[t.value]:
            tCellDict, tTableMat = WordHelper.resolveTable(tableDictAR[t.value])
            tableInfoDictAR[t.value] = WordHelper.TableInfo(tableDictAR[t.value], tCellDict, tTableMat)
        else:
            raise Exception(f"缺表{t.value}")

    del tableDictAR

    print()
    print("表格信息 =*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*")
    for tName, tInfo in tableInfoDictAR.items():
        print(f"look into table {tName}: ===============")
        cellDict = tInfo.cellDict
        for cTxt, mergedCells in cellDict.items():
            cleaned_text = cTxt.replace('\n', '').replace('\r', '')

            print(f"{cleaned_text}, ====> {mergedCells}")
        print(f"table {tName} done: ******************")
        print()

    print("^^^^^^^^^^^^^^^^^^^^^^^^^def table^^^^^^^^^^^^^^^^^^^^^^^^^")

    # 模型表
    table_ar_model = WordHelper.TableARModel(tableInfoDictAR[WordHelper.ETableAR.kModel.value],
                                             WordHelper.ETableAR.kModel)
    table_ar_model.printCells()

    model = groupedData.arModel
    if isinstance(model, TableData.ARModel):
        table_ar_model.fillProgName(model.programName)
        table_ar_model.fillModel(model.model)
        table_ar_model.fillKI(model.ki)

    # 工序表
    ar_seq = WordHelper.TableARSeq(tableInfoDictAR[WordHelper.ETableAR.kSeq.value], WordHelper.ETableAR.kSeq)
    ar_seq.printCells()

    arSeq = groupedData.arSeq
    tagPath = f'{configFilePath}\\key.png'
    ar_seq.addRows(arSeq.getAll(), tagPath)

    # 零件表
    ar_part = WordHelper.TableARPart(tableInfoDictAR[WordHelper.ETableAR.kPart.value], WordHelper.ETableAR.kPart)
    ar_part.printCells()

    arPart = groupedData.arPart
    ar_part.addRows(arPart.getAll())

    # 引用表
    ar_ref = WordHelper.TableARRef(tableInfoDictAR[WordHelper.ETableAR.kRef.value], WordHelper.ETableAR.kRef)
    ar_ref.printCells()

    arRef = groupedData.arRef
    ar_ref.fillNameAndDate(arRef.sign, arRef.signDate)
    for r in arRef.getForOnePage():
        ar_ref.addItem(r.seq, r.no, r.name, r.iss, r.final, r.ana)

    # 工程更改表
    # ar_eng_change = WordHelper.TableAREngChange(tableInfoDictAR[WordHelper.ETableAR.kEng.value],
    #                                             WordHelper.ETableAR.kEng)
    # ar_eng_change.printCells()
    # arChange = groupedData.arEngChange
    # ar_eng_change.addRows(arChange.getAll())

    # 保存修改后的文档
    doc.save(copied_file_path)
    print(f"文档已保存到: {copied_file_path}")
    return Path(copied_file_path)
    # os.startfile(copied_file_path)


def fillHeader(doc: Document, groupedData: DataGrouping.GroupData):
    print(f"doc.sections 个数为 '{len(doc.sections)}'")

    headerData = groupedData.header
    if not isinstance(headerData, TableData.Header):
        raise Exception("读取头部信息失败")

    for section_index, section in enumerate(doc.sections):
        header = section.header

        if header.is_linked_to_previous:
            continue

        for table in header.tables:
            for row_index, row in enumerate(table.rows):
                for col_index, cell in enumerate(row.cells):
                    clean_text = cell.text.strip()
                    print(f"Found header table cell: '{clean_text}'")
                    if clean_text == 'AR编号AR NO.':
                        target_col = col_index + 1
                        cTxt = headerData.no
                        table.cell(row_index, target_col).text = f'AR_{cTxt}'
                    elif clean_text == 'AR版次AR REV.':
                        target_col = col_index + 1
                        cTxt = headerData.rev
                        table.cell(row_index, target_col).text = cTxt
                    elif clean_text == 'AR名称 AR TITLE':
                        target_col = col_index + 1
                        cTxt = headerData.title
                        table.cell(row_index, target_col).text = cTxt
                    elif clean_text == '部件号PART NUMBER':
                        target_col = col_index + 1
                        model = groupedData.model
                        if isinstance(model, TableData.Model):
                            cTxt = headerData.no
                            table.cell(row_index, target_col).text = cTxt

        break
